import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Request } from 'express';
import { DECORATOR, EXCEPTION, JWT } from 'src/constants';
import { RuntimeException } from 'src/exceptions/runtime.exception';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private jwtService: JwtService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    // 反射当前方法是否存在 Public() 装饰器
    const isPublic = this.reflector.getAllAndOverride<boolean>(
      DECORATOR.IS_PUBLIC_KEY,
      [context.getHandler(), context.getClass()],
    );
    if (isPublic) {
      // 💡 存在 Public() 装饰器
      return true;
    }
    // ---------------------------- 分割线 ----------------------------
    // 👆上面会验证白名单，因为接口不需要验证用户是少数接口，使用 @Public() 装饰器来修饰就可以了
    // 👆上面就验证哪些不需要验证用户的接口，直接返回 true，表示验证通过
    // ---------------------------- 分割线 ----------------------------
    const request = context.switchToHttp().getRequest();
    const token = this.extractTokenFromHeader(request);
    if (!token) {
      throw new RuntimeException('TOKEN ERROR', EXCEPTION.NO_LOGIN);
    }
    try {
      const payload = await this.jwtService.verifyAsync(token, {
        secret: JWT.secret,
      });
      // 💡 我们在这里将 payload 分配给请求对象
      // 以便我们可以在路由处理程序中访问它
      request['user'] = payload;
    } catch {
      throw new RuntimeException('PAYLOAD ERROR', EXCEPTION.NO_LOGIN);
    }
    return true;
  }

  private extractTokenFromHeader(request: Request): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
}
